package com.smh.aiagent.rag;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.markdown.MarkdownDocumentReader;
import org.springframework.ai.reader.markdown.config.MarkdownDocumentReaderConfig;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shiminghui
 * @date 2025/6/1 16:04
 * @description: 读取本地的markdown文档
 */
@Component
@RequiredArgsConstructor // 动态生成构造函数
@Slf4j
public class LoveMarkdownDocumentLoader {
    private final ResourcePatternResolver resourcePatternResolver;

    public List<Document> loadMarkdownDocuments() {

        List<Document> markdownDocuments = new ArrayList<>();

        Resource[] resources = new Resource[0];
        try {
            resources = resourcePatternResolver.getResources("classpath:documents/markdown/*.md");
        } catch (IOException e) {
            log.error("Error loading markdown documents: {}", e.getMessage(), e);
        }
        for (Resource resource : resources) {

            String filename = resource.getFilename();
            // 截取文件名中的关键词
            String status = filename.substring(filename.length() - 6, filename.length() - 4);

            // 处理每一个资源,生成Document
            MarkdownDocumentReader reader = new MarkdownDocumentReader(resource,
                    MarkdownDocumentReaderConfig.builder()
                            .withHorizontalRuleCreateDocument(true) // 使用分割线 创建文档
                            .withAdditionalMetadata("file_name", resource.getFilename()) // 添加元信息
                            .withAdditionalMetadata("status", status)
                            .withIncludeBlockquote(false) // 是否包含代码块之类的
                            .withIncludeCodeBlock(false)
                            .build());
            List<Document> documents = reader.get();
            markdownDocuments.addAll(documents);
        }

        return markdownDocuments;
    }
}
